package com.jungle.client.utils;

import javafx.event.EventTarget;
import javafx.scene.Node;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.input.MouseEvent;

import java.util.Optional;
import java.util.function.Consumer;

public class TableViewUtil {
    private TableViewUtil() {
    }

    public static void traceTableRow(MouseEvent event, Consumer<TableRow<?>> consumer) {
        EventTarget target = event.getTarget();
        if (target instanceof Node node) {
            traceTableRow(node).ifPresent(consumer);
        }
    }

    private static Optional<TableRow<?>> traceTableRow(Node node) {
        if (node == null || node instanceof TableView<?>) {
            return Optional.empty();
        }
        if (node instanceof TableRow<?> tableRow) {
            return Optional.of(tableRow);
        }
        if (node instanceof TableCell<?, ?> tableCell) {
            return Optional.of(tableCell.getTableRow());
        }
        return traceTableRow(node.getParent());
    }
}
